<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="任务奖励" prop="taskRewards">
            <el-input v-model="queryParams.taskRewards" placeholder="请输入任务奖励" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否停用" prop="disableStatus">
            <el-select v-model="queryParams.disableStatus" placeholder="请选择是否停用" clearable style="width: 240px">
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="任务分组" prop="taskGroup">
            <el-select v-model="queryParams.taskGroup" placeholder="请选择任务分组" clearable style="width: 240px">
              <el-option
                v-for="dict in data.taskGroupOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mushcoin:userTaskManage:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['mushcoin:userTaskManage:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['mushcoin:userTaskManage:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Top" @click="handleImport()" v-hasPermi="['mushcoin:userTaskManage:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['mushcoin:userTaskManage:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userTaskManageList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务ID" align="center" prop="id" v-if="true" />
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="任务奖励" align="center" prop="taskRewards" />
        <el-table-column label="任务链接" align="center" prop="taskUrl" />
        <el-table-column label="任务分组" align="center" prop="taskGroup" />
        <el-table-column label="有效天数" align="center" prop="validDays" />
        <el-table-column label="logo图标" align="center" prop="iconImg" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.iconImg" :width="50" :height="50"/>
          </template>
        </el-table-column>

        <el-table-column label="是否停用" align="center" prop="disableStatus">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.disableStatus"/>
          </template>
        </el-table-column>

        <el-table-column label="创建日期" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['mushcoin:userTaskManage:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['mushcoin:userTaskManage:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改用户任务管理(H5)对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
      <el-form ref="userTaskManageFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务奖励" prop="taskRewards">
              <el-input v-model="form.taskRewards" placeholder="请输入任务奖励" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务链接" prop="taskUrl">
              <el-input v-model="form.taskUrl" placeholder="请输入任务链接" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="任务分组" prop="taskGroup">
              <el-input v-model="form.taskGroup" placeholder="请输入任务分组" />
            </el-form-item>
          </el-col>

          <el-form-item label="任务分组">
            <el-select v-model="form.taskGroup" placeholder="请输入任务分组" clearable style="width: 240px">
              <el-option
                v-for="dict in data.taskGroupOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-col :span="24">
            <el-form-item label="有效天数" prop="validDays">
              <el-input v-model="form.validDays" placeholder="请输入有效天数" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="logo图标" prop="iconImg">
              <image-upload v-model="form.iconImg" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否停用" prop="disableStatus">
              <el-radio-group v-model="form.disableStatus">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="parseInt(dict.value)" >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listUserTaskManage, getUserTaskManage, delUserTaskManage, addUserTaskManage, updateUserTaskManage } from '@/api/mushcoin/userTaskManage';
import { UserTaskManageVO, UserTaskManageQuery, UserTaskManageForm } from '@/api/mushcoin/userTaskManage/types';
import { globalHeaders } from '@/utils/request';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));
// 表格数据
const userTaskManageList = ref<UserTaskManageVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
// 选中数组
const ids = ref<Array<string | number>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userTaskManageFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 1,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/mushcoin/userTaskManage/importData'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserTaskManageForm = {
  taskName: undefined,
  taskRewards: undefined,
  taskUrl: undefined,
  taskGroup: undefined,
  validDays: "3",
  iconImg: undefined,
  disableStatus: 0
};
// 默认排序
const defaultSort = ref<any>({ prop: 'id', order: 'descending' });
const data = reactive<PageData<UserTaskManageForm, UserTaskManageQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    taskName: undefined,
    taskRewards: undefined,
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order,
    params: {},
    disableStatus: '0'
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    taskRewards: [
      { required: true, message: "任务奖励不能为空", trigger: "blur" }
    ],
    taskUrl: [
      { required: true, message: "任务链接不能为空", trigger: "blur" }
    ],
    iconImg: [
      { required: true, message: "logo图标不能为空", trigger: "blur" }
    ],
  },
  taskGroupOptions: [
    { value: 'Quest', label: 'Quest' },
    { value: 'Partner', label: 'Partner' },
    { value: 'Earn', label: 'Earn' }
  ]
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户任务管理(H5)列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUserTaskManage(queryParams.value);
  userTaskManageList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  userTaskManageFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const handleSortChange = (column: any) => {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserTaskManageVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加用户任务管理(H5)';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserTaskManageVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getUserTaskManage(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改用户任务管理(H5)';
};

/** 提交按钮 */
const submitForm = () => {
  userTaskManageFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserTaskManage(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserTaskManage(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserTaskManageVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户任务管理(H5)编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delUserTaskManage(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};


/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('mushcoin/userTaskManage/export', {
    ...queryParams.value
  }, `userTaskManage_${new Date().getTime()}.xlsx`)
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户任务管理(H5)导入';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('mushcoin/userTaskManage/importTemplate', {}, `userTaskManage_template.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});

</script>
